package com.metel.mservice.common.resolver;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.metel.mservice.common.bean.Countries;
import com.metel.mservice.common.bean.Country;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class CountryResolver {

	private Countries countries = new Countries();

	@Autowired
	public void setFilename(String filename) {
		Resource resource = new ClassPathResource(filename);
		try {
			XStream xstream = new XStream(new DomDriver());
			xstream.processAnnotations(Countries.class);
			this.countries = (Countries)xstream.fromXML(resource.getInputStream());
			this.countries.createMap();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	public Country resolve(HttpServletRequest request) {
		Region location = geoipDao.getRegion(RequestUtils.getClientIp(request));
		if (location == null) {
			return getDefaultCountry();
		} else {
			return resolveByIso2(location.countryCode);
		}
	}
	*/
	
	public Country resolveByIso2(String iso2) {
		Country country = getCountries().getCountryByIso2(iso2);
		if (country == null) {
			return getDefaultCountry();
		} else {
			return country;
		}
	}
	
	public Country resolveByIso3(String iso3) {
		Country country = getCountries().getCountryByIso3(iso3);
		if (country == null) {
			return getDefaultCountry();
		} else {
			return country;
		}
	}
	
	public Country getDefaultCountry() {
		return getCountries().getCountryByIso2(Countries.ISO2_SouthKorea);
	}
	
	private Countries getCountries() {
		return this.countries;
	}
	
	public List<Country> getAllCountries() {
		return getCountries().getCountries();
	}
	
}
